﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using LView.CMS.IServices;
using LView.CMS.Models;
using LView.CMS.Core;
using LView.CMS.ViewModels;
using System.Linq;
using LView.CMS.ViewModels.MyTask;

namespace LView.CMS.Services
{
    public class MyTaskService : ServiceBase, IMyTaskService
    {
        public (List<LMyTask>, int) GetMyTaskList(string userId)
        {
            var (myTaskList, myTaskCount) = MongodbHelper.Instance.FindList<LMyTask>(x => x.UserId == userId);
            return (myTaskList, (int)myTaskCount);
        }

        //public async Task<BaseResult> SaveExamProcess(LProcess input, string examId, List<MyExamAnswer> answerInfoDetails)
        //{
        //    var result = new BaseResult();
        //    try
        //    {
        //        var currentTask = await MongodbHelper.Instance.FindEntityAsync<LTask>(x => x.Id == input.TaskId);

        //        var dbProcess1 = await MongodbHelper.Instance.FindEntityAsync<LProcess>(
        //                            x => x.TaskId == input.TaskId &&
        //                            x.CourseId == input.CourseId &&
        //                            x.UserId == input.UserId);

        //        //result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
        //        //result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
        //        return result;
        //    }
        //    catch (Exception ex)
        //    {
        //        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
        //        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg + $":{ex.Message}";
        //    }
        //    return result;
        //}

        public async Task<BaseResult> SaveLProcess(LProcess input, decimal timeOfThisTimes)
        {
            var result = new BaseResult();
            try
            {
                #region 当前课程进度更新
                var currentTask = await MongodbHelper.Instance.FindEntityAsync<LTask>(x => x.Id == input.TaskId);
                var dbProcess = await MongodbHelper.Instance.FindEntityAsync<LProcess>(
                                x => x.TaskId == input.TaskId &&
                                x.CourseId == input.CourseId &&
                                x.UserId == input.UserId);
                var allCourse = new List<Course>();
                currentTask.Category.ForEach(x =>
                {
                    x.Course.ForEach(c => { allCourse.Add(c); });
                });
                var currentCourse = allCourse.First<Course>(x => x.CourseId == input.CourseId);
                var courseRequiredPeriod = currentCourse.CoursePeriod;
                var courseRequiredScore = currentCourse.CourseScore;
                var courseGotPeriod = dbProcess.CourseGotPeriod + timeOfThisTimes;
                var coursePercent = dbProcess.Percent;
                if (courseGotPeriod > courseRequiredPeriod * 60)
                    coursePercent = 100;
                else
                    coursePercent = Math.Round(courseGotPeriod / (courseRequiredPeriod * 60), 2) * 100;
                var courseGotScore = Math.Round((decimal)courseGotPeriod / (courseRequiredPeriod * 60), 2) * courseRequiredScore;

                dbProcess.CourseGotPeriod = (int)courseGotPeriod;
                dbProcess.CourseGotScore = (int)courseGotScore > courseRequiredScore ? courseRequiredScore : (int)courseGotScore;
                dbProcess.Percent = coursePercent;
                await MongodbHelper.Instance.UpdateOneAsync(
                        x => x.TaskId == input.TaskId &&
                        x.CourseId == input.CourseId &&
                        x.UserId == input.UserId, dbProcess);
                #endregion

                #region 更新我的任务进度
                var myTask = await MongodbHelper.Instance.FindEntityAsync<LMyTask>(
                         x => x.UserId == input.UserId &&
                         x.TaskId == input.TaskId);

                //查看该User有多少课程
                var (list, total) = await MongodbHelper.Instance.FindListAsync<LProcess>(
                            x => x.UserId == input.UserId &&
                            x.TaskId == input.TaskId);
                //更新当前课程总的百分比
                if (list.Count(x => x.CourseId != input.CourseId && x.Percent != 100) == 0 && coursePercent == 100)
                {
                    myTask.Percent = 100;
                    myTask.Status = 1;
                }
                else
                {
                    //计算我的任务总的百分比
                    var totalPercent = list.Where(x => x.CourseId != input.CourseId).Sum(x => x.Percent) + coursePercent;
                    myTask.Percent = totalPercent / list.Count();
                }
                //更新当前课程总的百分比
                await MongodbHelper.Instance.UpdateOneAsync(x => x.UserId == input.UserId &&
                            x.TaskId == input.TaskId, myTask);
                #endregion
                result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
            }
            catch (Exception ex)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg + $":{ex.Message}";
            }
            return result;
        }

        public BaseResult SaveExamProcess(string examId, LProcess input, List<MyExamAnswer> answerInfoDetails)
        {
            var result = new BaseResult();
            try
            {
                #region 当前课程进度更新
                //var currentExam = await MongodbHelper.Instance.FindEntityAsync<LExam>(x => x.Id == examId);
                var currentExam = MongodbHelper.Instance.FindEntity<LExam>(x => x.Id == examId);
                var dbProcess = MongodbHelper.Instance.FindEntity<LProcess>(
                                x => x.TaskId == input.TaskId &&
                                x.CourseId == input.CourseId &&
                                x.UserId == input.UserId);

                var examPassScore = currentExam.PassScore;
                var currentExamGotScore = 0;
                foreach (var answer in answerInfoDetails)
                {
                    var answerChooseOpt = currentExam.ExamQuestions.First(x => x.Id == answer.QuestionId).RigthOptionIds;
                    if (answer.QuestionChooseIds != null)
                    {
                        if (answer.QuestionChooseIds.Count == answerChooseOpt.Count)
                        {
                            var allEqual = true;
                            foreach (var optItem in answer.QuestionChooseIds)
                            {
                                if (answerChooseOpt.Where(x => x.Contains(optItem)).Count() == 0)
                                {
                                    allEqual = false;
                                }
                            }
                            if (allEqual)
                            {
                                currentExamGotScore += int.Parse(answer.QuestionScore);
                            }
                        }
                    }
                }
                var coursePercent = 0;
                var allCourse = new List<Course>();

                var currentTask = MongodbHelper.Instance.FindEntity<LTask>(x => x.Id == input.TaskId);
                currentTask.Category.ForEach(x =>
                {
                    x.Course.ForEach(c => { allCourse.Add(c); });
                });
                var currentCourse = allCourse.First<Course>(x => x.CourseId == input.CourseId);
                if (currentExamGotScore >= examPassScore)
                {
                    dbProcess.CourseGotPeriod = currentCourse.CoursePeriod;
                    dbProcess.CourseGotScore = currentCourse.CourseScore;
                    coursePercent = 100;
                    dbProcess.Percent = coursePercent;
                    MongodbHelper.Instance.UpdateOne(
                        x => x.TaskId == input.TaskId &&
                        x.CourseId == input.CourseId &&
                        x.UserId == input.UserId, dbProcess);

                    #region 更新我的任务进度
                    var myTask = MongodbHelper.Instance.FindEntity<LMyTask>(
                         x => x.UserId == input.UserId &&
                         x.TaskId == input.TaskId);

                    //查看该User有多少课程
                    var (list, total) = MongodbHelper.Instance.FindList<LProcess>(
                                x => x.UserId == input.UserId &&
                                x.TaskId == input.TaskId);
                    //更新当前课程总的百分比
                    if (list.Count(x => x.CourseId != input.CourseId && x.Percent != 100) == 0 && coursePercent == 100)
                    {
                        myTask.Percent = 100;
                        myTask.Status = 1;
                    }
                    else
                    {
                        //计算我的任务总的百分比
                        var totalPercent = list.Where(x => x.CourseId != input.CourseId).Sum(x => x.Percent) + coursePercent;
                        myTask.Percent = totalPercent / list.Count();
                    }
                    //更新当前课程总的百分比
                    MongodbHelper.Instance.UpdateOne(x => x.UserId == input.UserId &&
                                x.TaskId == input.TaskId, myTask);
                    #endregion

                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = $"本次测验成绩:{currentExamGotScore},已合格";
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = $"本次测验成绩:{currentExamGotScore},未达到合格线";
                }
                #endregion

            }
            catch (Exception ex)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg + $":{ex.Message}";
            }
            return result;
        }
    }
}
